﻿using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using MiniExcelLibs;
using HandyControl.Controls;
using System.Windows.Input;
using Infov1.Models;
using Infov1.Models.WorkForm;
using System.Linq;
using Infov1.Models.Communication;
using Infov1.Models.WorkRecord;
using Infov1.Commands;
using MiniExcelLibs.OpenXml;
using SqlSugar;
using System.Collections.Generic;
using Infov1.Views.WorkForm;



namespace Infov1.ViewModels.WorkForm
{
    public class WorkDetailViewModel : ViewModelBase
    {
        private readonly SqlSugar.ISqlSugarClient _db;
        //开始日期
        private DateTime _startDate;
        public DateTime StartDate
        {
            get => _startDate;
            set {
                _startDate = value;
                OnPropertyChanged(nameof(StartDate));
            }
        }
        //定义结束日期
        private DateTime _endDate;
        public DateTime EndDate
        {
            get => _endDate;
            set
            {
                _endDate = value;
                OnPropertyChanged(nameof(EndDate));
            }
        }
        //定义客户列表
        private ObservableCollection<CustomerInfoModel> _customers = new ObservableCollection<CustomerInfoModel>();
        public ObservableCollection<CustomerInfoModel> Customers
        {
            get => _customers;
            set
            {
                _customers = value;
                OnPropertyChanged(nameof(Customers));
            }
        }
        // 定义操作员列表
        private ObservableCollection<AdminModel> _admins = new ObservableCollection<AdminModel>();
        public ObservableCollection<AdminModel> Admins
        {
            get => _admins;
            set => SetProperty(ref _admins, value);
        }
        //定义工作信息列表
        private ObservableCollection<Infov1.Models.WorkRecord.WorkRecordModel> _workRecords = new ObservableCollection<Infov1.Models.WorkRecord.WorkRecordModel>();
        public ObservableCollection<Infov1.Models.WorkRecord.WorkRecordModel> WorkRecords
        {
            get => _workRecords;
            set => SetProperty(ref _workRecords, value);
        }
        //定义选中的操作员
        private AdminModel _selectedOperator;
        public AdminModel SelectedOperator
        {
            get => _selectedOperator;
            set {
                SetProperty(ref _selectedOperator, value);
                    
                  }
        }
        //定义选中的客户
        private CustomerInfoModel _selectedCustomer;
        public CustomerInfoModel SelectedCustomer
        {
            get => _selectedCustomer;
            set {
                SetProperty(ref _selectedCustomer, value);
                /*if (value != null)
                {
                    var message = new System.Text.StringBuilder();
                    message.AppendLine($"客户名称：{value.CompanyName}");
                    message.AppendLine($"客户编号：{value.CustomerCode}");
                    message.AppendLine($"客户ID：{value.Id}");
                    message.AppendLine($"联系人：{value.ContactPerson}");
                    message.AppendLine($"联系电话：{value.ContactPhone}");

                    System.Windows.MessageBox.Show(message.ToString(), "选中的客户信息");
                }*/
            }
        }
        // 定义事项列表属性
        private ObservableCollection<CommunicationTypeModel> _commTypes = new ObservableCollection<CommunicationTypeModel>();
        public ObservableCollection<CommunicationTypeModel> CommTypes
        {
            get => _commTypes;
            set => SetProperty(ref _commTypes, value);
        }
        // 定义选中的事项属性
        private CommunicationTypeModel _selectedCommType;
        public CommunicationTypeModel SelectedCommType
        {
            get => _selectedCommType;
            set => SetProperty(ref _selectedCommType, value);
        }
        //定义工作信息查询命令
        private ICommand _queryCommand;
        public ICommand QueryCommand
        {
            get
            {
                return _queryCommand ?? (_queryCommand = new AsyncRelayCommand(LoadWorkRecordAsync));
            }
        }
        // 定义添加删除命令
        private ICommand _deleteCommand;
        public ICommand DeleteCommand
        {
            get
            {
                return _deleteCommand ?? (_deleteCommand = new AsyncRelayCommand<Infov1.Models.WorkRecord.WorkRecordModel>(DeleteWorkRecordAsync));
            }
        }
        //定义导出命令
        private ICommand _exportCommand;
        public ICommand ExportCommand
        {
            get
            {
                return _exportCommand ?? (_exportCommand = new AsyncRelayCommand(ExportToExcelAsync));
            }
        }
        //初始化数据
        public WorkDetailViewModel() {
          

            //初始化数据库连接
            _db = DbContext.GetConnection();
            //初始化开始和结束时间
            StartDate = DateTime.Now;
            EndDate = DateTime.Now;
            //初始化编辑命令
            EditCommand = new RelayCommand<Infov1.Models.WorkRecord.WorkRecordModel>(ExecuteEdit);
            // 初始化数据
            InitializeAsync();
        }
        //初始化方法
        private async void InitializeAsync()
        {
            try
            {
                await LoadCurtomers();
                await LoadAdmins();
               // await LoadWorkRecordAsync();
                // 加载事项列表
                await LoadCommTypes();
                // 初始化命令
                
            }
            catch (Exception ex)
            {
                Growl.Error($"初始化数据失败：{ex.Message}");
            }
        }
        //加载客户列表
        private async Task LoadCurtomers()
        {
            try
            {
                var customers =await  _db.Queryable<CustomerInfoModel>()
                    .ToListAsync();
                // 添加"全部"选项
                customers.Insert(0, new CustomerInfoModel
                {
                    Id = -1,
                    CompanyName = "全部"
                });
                Customers = new ObservableCollection<CustomerInfoModel>(customers);
            }
            catch (Exception ex)
            {
                Growl.Error($"加载客户列表失败：{ex.Message}");
            }
        }
        //加载操作员列表
        private async Task LoadAdmins()
        {
            try
            {
                var admins =await  _db.Queryable<AdminModel>()
                    .Where(a=>a.Username.ToString() != "1001")
                    .ToListAsync();
                // 添加"全部"选项
                admins.Insert(0, new AdminModel
                {
                    Username = "",
                    Name = "全部"
                });
                Admins = new ObservableCollection<AdminModel>(admins);
                //设置默认操作员
                string currentAdminName = Application.Current.Properties["AdminName"]?.ToString();
                SelectedOperator = Admins.FirstOrDefault(a => a.Username == currentAdminName);
            }
            catch (Exception ex)
            {
                Growl.Error($"加载操作员列表失败：{ex.Message}");
            }
        }
        // 加载事项列表方法
        private async Task LoadCommTypes()
        {
            try
            {
                var types = await _db.Queryable<CommunicationTypeModel>().ToListAsync();

                // 添加"全部"选项
                types.Insert(0, new CommunicationTypeModel
                {
                    TypeCode = "",
                    TypeName = "全部"
                });

                CommTypes = new ObservableCollection<CommunicationTypeModel>(types);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载事项列表失败：{ex.Message}");
            }
        }
        //加载工作登记列表方法
        private async Task LoadWorkRecordAsync()
        {
            if (EndDate < StartDate)
            {
                System.Windows.MessageBox.Show($"开始日期不能大于结束日期！");
                return;
            }
            try
            {
                var startTime = StartDate.Date;
                var endTime = EndDate.Date.AddDays(1).AddSeconds(-1);
                // 基本查询
                var records = await _db.Queryable<Infov1.Models.WorkRecord.WorkRecordModel>()
                    .LeftJoin<CustomerInfoModel>((w, c) => w.CustomerId == c.Id)  // 使用 CustomerId 关联
                    .LeftJoin<CommunicationTypeModel>((w, c, t) => w.CommTypeCode == t.TypeCode)
                    //筛选时间
                    .Where(w => w.CreationTime >= startTime && w.CreationTime <= endTime)
                    //筛选操作员
                    .WhereIF(SelectedOperator != null && !string.IsNullOrEmpty(SelectedOperator.Username),   
                                     w => w.Operator == SelectedOperator.Username)
                    //筛选客户
                   .WhereIF(SelectedCustomer != null && SelectedCustomer.Id > 0,  // 排除 -1 或 0
                                     w => w.CustomerId == SelectedCustomer.Id)
                    // 筛选事项
                    .WhereIF(SelectedCommType != null && !string.IsNullOrEmpty(SelectedCommType.TypeCode),
                                     w => w.CommTypeCode == SelectedCommType.TypeCode) // 添加事项筛选条件
                    .Select((w, c, t) => new Infov1.Models.WorkRecord.WorkRecordModel()  // 直接返回 WorkRecordModel
                    {
                        RecordId = w.RecordId,
                        CreationTime = w.CreationTime,
                        CustomerCode = w.CustomerCode,
                        CustomerId = w.CustomerId,
                        CommTypeCode = w.CommTypeCode,
                        IsRemote = w.IsRemote,
                        HandleTypeText = w.IsRemote == true ? "远程" : "电话",  
                        Details = w.Details,
                        Result = w.Result,
                        Operator = w.Operator,
                        Customer = new WorkRecordCustomerModel
                        {
                            CompanyName = c.CompanyName
                        },
                        CommType = new CommunicationTypeModel
                        {
                            TypeName = t.TypeName
                        }
                    })
                    .OrderByDescending(w => w.CreationTime)
                    .ToListAsync();

            

                Application.Current.Dispatcher.Invoke(() =>
                {
                    WorkRecords.Clear();
                    foreach (var record in records)
                    {
                        WorkRecords.Add(record);
                    }
                });
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载工作信息失败！：{ex.Message}");
                // 打印详细错误信息以便调试
                System.Diagnostics.Debug.WriteLine($"错误详情：{ex}");
            }
        }
       //删除方法
        private async Task DeleteWorkRecordAsync(Infov1.Models.WorkRecord.WorkRecordModel record)
        {
            try
            {
                if (record == null) return;

                var result = HandyControl.Controls.MessageBox.Show(
                    $"确定要删除这条记录吗？\n客户：{record.Customer?.CompanyName}\n时间：{record.CreationTime:yyyy-MM-dd HH:mm:ss}",
                    "确认删除",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    // 从数据库删除
                    await _db.Deleteable<Infov1.Models.WorkRecord.WorkRecordModel>()
                            .Where(w => w.RecordId == record.RecordId)
                            .ExecuteCommandAsync();

                    // 从列表中移除
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        WorkRecords.Remove(record);
                    });

                    Growl.Success("删除成功！");
                }
            }
            catch (Exception ex)
            {
                Growl.Error($"删除失败：{ex.Message}");
            }
        }
        //导出方法
        private async Task ExportToExcelAsync()
        {
            try
            {
                if (WorkRecords.Count == 0)
                {
                    System.Windows.MessageBox.Show("没有可导出的数据！");
                    return;
                }

                var dialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter = "Excel文件|*.xlsx",
                    DefaultExt = ".xlsx",
                    FileName = $"工作记录_{DateTime.Now:yyyyMMddHHmmss}"
                };

                if (dialog.ShowDialog() == true)
                {
                    // 准备数据
                    var exportData = WorkRecords.Select(record => new Dictionary<string, object>
                    {
                        ["处理时间"] = record.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        ["客户名称"] = record.Customer?.CompanyName ?? "",
                        ["事项类型"] = record.CommType?.TypeName ?? "",
                        ["处理详情"] = record.Details ?? "",
                        ["处理结果"] = record.Result ?? "",
                        ["处理方式"] = record.HandleTypeText ?? "",
                        ["操作员"] = record.Operator ?? ""
                    }).ToList();

                    // 使用 MiniExcel 导出
                    await MiniExcel.SaveAsAsync(dialog.FileName, exportData);
                    System.Windows.MessageBox.Show("导出成功！");
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"导出失败：{ex.Message}");
            }
        }
        //编辑命令
        public ICommand EditCommand { get; }
        private void ExecuteEdit(Infov1.Models.WorkRecord.WorkRecordModel record)
        {
            if (record == null) return;

            try
            {
                var editVM = new EditWorkRecordViewModel(record, _db, async () =>
                {
                    // 刷新数据的回调
                    await LoadWorkRecordAsync();  // 使用已有的加载方法
                });

                var editWindow = new EditWorkRecordWindow
                {
                    DataContext = editVM,
                 
                };

                editWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                Growl.Error($"打开编辑窗口失败：{ex.Message}");
            }
        }
        // 添加查询方法
        private async Task QueryRecords()
        {
            try
            {
                var startTime = StartDate.Date;
                var endTime = EndDate.Date.AddDays(1).AddSeconds(-1);

                var records = await _db.Queryable<Infov1.Models.WorkRecord.WorkRecordModel>()
                    .LeftJoin<CustomerInfoModel>((w, c) => w.CustomerId == c.Id)
                    .LeftJoin<CommunicationTypeModel>((w, c, t) => w.CommTypeCode == t.TypeCode)
                    .Where(w => w.CreationTime >= startTime && w.CreationTime <= endTime)
                    .WhereIF(SelectedOperator != null && !string.IsNullOrEmpty(SelectedOperator.Username),
                             w => w.Operator == SelectedOperator.Username)
                    .WhereIF(SelectedCustomer != null && SelectedCustomer.Id > 0,
                             w => w.CustomerId == SelectedCustomer.Id)
                    .WhereIF(SelectedCommType != null && !string.IsNullOrEmpty(SelectedCommType.TypeCode),
                             w => w.CommTypeCode == SelectedCommType.TypeCode)
                    .Select((w, c, t) => new Infov1.Models.WorkRecord.WorkRecordModel
                    {
                        RecordId = w.RecordId,
                        CreationTime = w.CreationTime,
                        CustomerCode = w.CustomerCode,
                        CustomerId = w.CustomerId,
                        CommTypeCode = w.CommTypeCode,
                        IsRemote = w.IsRemote,
                        HandleTypeText = w.IsRemote == true ? "远程" : "电话",
                        Details = w.Details,
                        Result = w.Result,
                        Operator = w.Operator,
                        Customer = new WorkRecordCustomerModel
                        {
                            CompanyName = c.CompanyName
                        },
                        CommType = new CommunicationTypeModel
                        {
                            TypeName = t.TypeName
                        }
                    })
                    .OrderByDescending(w => w.CreationTime)
                    .ToListAsync();

                WorkRecords = new ObservableCollection<Infov1.Models.WorkRecord.WorkRecordModel>(records);
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Show(
                    $"查询失败：{ex.Message}",
                    "错误",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
        
    }
}